import {
  CrumbItem,
  CrumbType,
  RouterItem,
  PathMapItem,
  RouterType,
} from './router-types'
const moduleList: any[] = []
const routerList: any[] = []

const importAll = (r: any) => {
  Object.values(r).forEach((key: any) => {
    if (Array.isArray(key.default)) {
      moduleList.push(...key.default)
    } else {
      moduleList.push(key.default)
    }
    return moduleList
  })
}

const getRoute = (node: RouterItem) => {
  const routes: any[] = []
  function _deep(node: RouterItem, reduceInfo: any) {
    const nodes: RouterType = []
    // 有name的就是页面
    if (node.name) {
      routes.push({
        name: node.name,
        path: pathSplicing(reduceInfo.meta.crumbs) + node.path,
        component: node.component,
        // crumbs: [
        //   ...reduceInfo.crumbs,
        //   {
        //     title: node.title,
        //     name: node.name,
        //     path: pathSplicing(reduceInfo.crumbs) + node.path,
        //   },
        // ],
        meta: {
          ...node.meta,
          title: node.title,
          selectLeftMenu: node.selectLeftMenu,
          crumbs: [
            ...reduceInfo.meta.crumbs,
            {
              title: node.title,
              name: node.name,
              path: pathSplicing(reduceInfo.meta.crumbs) + node.path,
            },
          ],
        },
      })
    }
    if (node != null) {
      nodes.push(node)
      const childrens = node.children || []
      if (childrens.length) {
        const nextInfo = {
          path: node.name
            ? pathSplicing(reduceInfo.meta.crumbs) + node.path
            : '',

          meta: {
            title: node.title,
            ...node.meta,
            selectLeftMenu: node.selectLeftMenu,
            crumbs: [
              ...reduceInfo.meta.crumbs,
              {
                title: node.title,
                name: node.name,
                path: node.path,
                aliasName: node.aliasName,
              },
            ],
          },
        }
        for (let i = 0; i < childrens.length; i++) _deep(childrens[i], nextInfo)
      }
    }
    return nodes
  }
  _deep(node, {
    path: '',
    meta: {
      crumbs: [],
    },
  })
  return routes
}

const pathSplicing = (arr: CrumbType) => {
  if (!arr.length) {
    return ''
  }
  let pathUrl = ''
  arr.forEach((item: CrumbItem) => {
    pathUrl += item.path
  })
  return pathUrl
}

importAll(import.meta.globEager('./modules/*.ts'))

moduleList.forEach((m: RouterItem) => {
  routerList.push(...getRoute(m))
})

const pathMap: PathMapItem = {}
routerList.forEach((item: RouterItem) => {
  // 有name才添加
  item.name && (pathMap[item.name] = item)
})

export default {
  routerList,
  moduleList,
  pathMap,
}
